<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use common\models\OmsArticle;
use common\models\SysCategory;

class ArticleController extends Controller {
//    public $layout = "blog"; //设置使用的布局文件

    /**
     * 博客列表页
     */
    public function actionIndex() {
        $query = new \yii\db\Query();
        $query->select(['id','author','title','content','add_time'])->from("yc_oms_article");
        $query->andFilterWhere(['status' => 1]);
        
        $categoryId = \Yii::$app->request->get('category','');
        if(!empty($categoryId)) {
            $query->andFilterWhere(['type_id' => $categoryId]);
        }
        
        $archieveTime = \Yii::$app->request->get('archieve','');
        if(!empty($archieveTime)) {
            $query->andFilterWhere(['between', 'add_time', $archieveTime.' 00:00:00', $archieveTime.' 23:59:59']);
        }
        //获取文章列表
        $article = $query->orderBy('add_time DESC')->all();
        
        $archieve = $this->getArchieve();//获取文章归类
        
        $category = $this->getCategory();//获取文章分类
        
        return $this->render('index', [
                    'article' => $article,
                    'archieve' => $archieve,
                    'category' => $category,
        ]);
    }

    /**
     * 博客内容页
     */
    public function actionBlog() {
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        $article = \Yii::$app->cache->get('articleIndex' . date("Ymd") . $id);
        if (empty($article)) {
            $article = OmsArticle::find()->where(['id' => $id])->one();
            \Yii::$app->cache->set('articleIndex' . date("Ymd") . $id, $article, 3600 * 1);
        }
        $archieve = $this->getArchieve();
        $category = $this->getCategory();
        return $this->render('blog', [
                    'article' => $article,
                    'archieve' => $archieve,
                    'category' => $category,
        ]);
    }

    /**
     * 获取分类
     * @return array
     */
    public function getCategory() {
        $category = SysCategory::find('type_name')->orderBy('sort')->asArray()->all();
        //获取分类下文章的数量
        foreach ($category as $k => $v) {
            $category[$k]['num'] = OmsArticle::find('id')->where(['type_id' => $v['id']])->count();
        }
        return $category;
    }

    /**
     * 获取文章归档
     * @return array
     */
    public function getArchieve() {
        $sql = "SELECT 
                FROM_UNIXTIME(UNIX_TIMESTAMP(add_time), '%Y-%m-%d') 'time',
                COUNT(*) 'num'
            FROM
                yc_oms_article
            WHERE
                status = 1
            GROUP BY time";
        return \Yii::$app->db->createCommand($sql)->queryAll();
    }

}
